//
//  MoodFormViewController.m
//  nonghubao
//
//  Created by 王 文彬 on 13-1-29.
//  Copyright (c) 2013年 mypocketbaby. All rights reserved.
//

//  -业务逻辑细节说明-
//
//  @abstract      本类用于发布一个商讯、或推荐一个商品信息。

//  @discussion    发布商品推荐的时候，没有图片拾取器，要隐藏图片拾取框，并且将圈子选择框向上移动
//

//  @notes          


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

#import "MoodFormViewController.h"
#import "Config.h"
#import "Helper.h"
#import <QuartzCore/QuartzCore.h>
#import "CirclePickerViewController.h"
#import "JMFBase.h"

@interface MoodFormViewController ()

@end

@implementation MoodFormViewController

@synthesize dynamicID = _dynamicID;
@synthesize productID = _productID;
@synthesize formType    = _formType;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //背景
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    //导航栏左按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    _contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 8, 300, 155)];
    _contentTextView.layer.cornerRadius = 3;
    _contentTextView.layer.borderColor = [_SYS_COLOR_005 CGColor];
    _contentTextView.layer.borderWidth = 1.0f;
    _contentTextView.text = [self choosePlaceholder];
    _contentTextView.backgroundColor = [UIColor whiteColor];
    _contentTextView.returnKeyType = UIReturnKeyDone;
    _contentTextView.delegate = (id)self;
    _contentTextView.font = _SYS_FONT_006;
    _contentTextView.textColor = _SYS_COLOR_003;
    [self.view addSubview:_contentTextView];

    
    //字数统计
    _countLabel = [[UILabel alloc] initWithFrame:CGRectMake(280, 165, 30, 15)];
    _countLabel.text = @"140";
    _countLabel.font = _SYS_FONT_002;
    _countLabel.textColor = _SYS_COLOR_002;
    _countLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_countLabel];
    
    
    //图片框
    _imagesView = [[UIView alloc] initWithFrame:CGRectMake(10, 182, 300, 75)];
    _imagesView.layer.cornerRadius = 3;
    _imagesView.layer.borderColor = [_SYS_COLOR_002 CGColor];
    _imagesView.layer.borderWidth = 1.0f;
    _imagesView.backgroundColor = _SYS_COLOR_004;
    [self.view addSubview:_imagesView];
    
    //图片1
    _thumbImageButton1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 65, 65)];
    _thumbImageButton1.tag = 1;
    [_thumbImageButton1 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal] ;
    [_thumbImageButton1 addTarget:self action:@selector(thumbImageButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    [_imagesView addSubview:_thumbImageButton1];
    
    //图片2
    _thumbImageButton2 = [[UIButton alloc] initWithFrame:CGRectMake(85, 5, 65, 65)];
    _thumbImageButton2.tag = 2;
    [_thumbImageButton2 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal] ;
    [_thumbImageButton2 addTarget:self action:@selector(thumbImageButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    _thumbImageButton2.hidden = true;
    [_imagesView addSubview:_thumbImageButton2];
    
    //图片3
    _thumbImageButton3 = [[UIButton alloc] initWithFrame:CGRectMake(160, 5, 65, 65)];
    _thumbImageButton3.tag = 3;
    [_thumbImageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal] ;
    [_thumbImageButton3 addTarget:self action:@selector(thumbImageButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    _thumbImageButton3.hidden = true;
    [_imagesView addSubview:_thumbImageButton3];
    
    
    //圈子框
    _circleView = [[UIView alloc] initWithFrame:CGRectMake(10, 265, 300, 45)];
    _circleView.layer.cornerRadius = 3;
    _circleView.layer.borderColor = [_SYS_COLOR_005 CGColor];
    _circleView.backgroundColor = [UIColor whiteColor];
    _circleView.layer.borderWidth = 1.0f;

    [self.view addSubview:_circleView];
    
    //圈子按钮
    _circleButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 120, 25)];
    _circleButton.titleLabel.font = _SYS_FONT_001;
    [_circleButton setTitle:_L(@"btn_circle_02") forState:UIControlStateNormal];
    [_circleButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_007_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_circleButton addTarget:self action:@selector(circleButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    [_circleView addSubview:_circleButton];
    
    //圈子框的分割线
    UIImageView* lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, 300, 1)];
    lineImageView.image = [UIImage imageNamed:@"line_292"];
    
    [_circleView addSubview:lineImageView];
    
    //圈子文字
    _circleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 45, 280, 20)];
    _circleLabel.backgroundColor = [UIColor clearColor];
    [_circleView addSubview:_circleLabel];
    
    
    //提交按钮
    _submitButton = [[UIButton alloc] initWithFrame:CGRectMake(10, _SYS_FRAME_HEIGHT - 44 - 44 -10, 300, 44)];
    _submitButton.titleLabel.font = _SYS_FONT_009;
    [_submitButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_006_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_submitButton addTarget:self action:@selector(submitButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    if (_formType == MoodFormTypeBusinessInfo) {
        [_submitButton setTitle:_L(@"btn_yes_06") forState:UIControlStateNormal];
    }
    else {
        [_submitButton setTitle:_L(@"btn_yes_51") forState:UIControlStateNormal];
    }
    [self.view addSubview:_submitButton];

    [self redrawView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    if (iOS7) {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    }
}

#pragma mark - 返回按钮流程

// 返回按钮事件
//
- (void)backButtonEvent
{
    if ((_contentTextView.text.length > 0 && ![_contentTextView.text isEqualToString:[self choosePlaceholder]]) || _thumbImage1 != nil || _thumbImage2 != nil || _thumbImage3 != nil) {
        
        NSString* alertString = _formType == MoodFormTypeBusinessInfo ? _L(@"alert_88") : _L(@"alert_98");
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:alertString delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        [alertView show];
    }
    else {
        [self.navigationController dismissModalViewControllerAnimated:true];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}

#pragma mark - 按钮事件方法
// 保存按钮事件
- (void)saveButtonEvent
{
    
}

// 图片按钮事件
//
- (void)thumbImageButtonEvent:(id)sender
{
    UIButton *selectedButton = (UIButton *)sender;
    
    UIActionSheet *actionSheet;
    if ((selectedButton.tag == 1 && _thumbImage1 != nil) || (selectedButton.tag == 2 && _thumbImage2 != nil) || (selectedButton.tag == 3 && _thumbImage3 != nil)) {
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:_L(@"btn_no_01") destructiveButtonTitle:nil otherButtonTitles:_L(@"btn_photo_01"), _L(@"btn_photo_02"), _L(@"btn_photo_03"), nil];
        actionSheet.destructiveButtonIndex = 2;
    }
    else {
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:_L(@"btn_no_01") destructiveButtonTitle:nil otherButtonTitles:_L(@"btn_photo_01"), _L(@"btn_photo_02"), nil];
    }

    actionSheet.tag = selectedButton.tag;
    [actionSheet showInView:self.view];
    
}

// 选择圈子按钮事件
//
- (void)circleButtonEvent
{
    CirclePickerViewController *circlePickerVC;
    
    if (_circlePickerNC == nil) {
        
        circlePickerVC = [[CirclePickerViewController alloc] initWithStyle:UITableViewStyleGrouped];
        
        _circlePickerNC = [[UINavigationController alloc] initWithRootViewController:circlePickerVC];

        [Helper navigationControllerCommonStyle:_circlePickerNC];
    }
    
    circlePickerVC.delegate = (id)self;
    [self.navigationController presentModalViewController:_circlePickerNC animated:true];
}

// 提交按钮事件
//
- (void)submitButtonEvent
{
    [_contentTextView resignFirstResponder];
    
    if (_contentTextView.text.length == 0 || [_contentTextView.text isEqualToString:[self choosePlaceholder]]) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_25")];   //请填写你想要发布的内容
        return;
    }
    
    if (_circleIDString == nil || _circleIDString.length == 0) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_26")];   //请选择要发布的圈子
        return;
    }
    
    
    JSONRequest* request;
    if (_formType == MoodFormTypeBusinessInfo) {
        
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_MOON_ADD];
        if (_thumbImage1) {
            [request setValue:[Helper compressImageData:_thumbImage1 withStyle:PictureStyleNormal] forParameter:@"image1"];
        }
        if (_thumbImage2) {
            [request setValue:[Helper compressImageData:_thumbImage2 withStyle:PictureStyleNormal] forParameter:@"image2"];
        }
        if (_thumbImage3) {
            [request setValue:[Helper compressImageData:_thumbImage3 withStyle:PictureStyleNormal] forParameter:@"image3"];
        }
    }
    else {
        
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_RECOMMEND_ADD];
        [request setValue:[NSString stringWithFormat:@"%i", _dynamicID] forParameter:@"dynamicId"];
        
        if (_productID > 0) {
            [request setValue:[NSString stringWithFormat:@"%i", _productID] forParameter:@"productId"];
        }
    }

    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_05");
    request.requestMode = RequestModeMultiPart;
    
    [request setValue:_circleIDString forParameter:@"circleIds"];
    [request setValue:_contentTextView.text forParameter:@"content"];
    [request asynchronous];
}


#pragma mark - CirclePickDelegate

// 圈子拾取协议方法
- (void)circlesPicked:(NSArray *)circles
{
    if (circles.count == 0) {
        if (_formType == MoodFormTypeBusinessInfo) {
            _circleView.frame = CGRectMake(10, 265, 300, 45);
        }else{
            _circleView.frame = CGRectMake(10, 182, 300, 45);
        }
        
        [_circleLabel setHidden:YES];
        return;
    }else{
        [_circleLabel setHidden:NO];
        if (_formType == MoodFormTypeBusinessInfo) {
            _circleView.frame = CGRectMake(10, 265, 300, 79);
        }else{
            _circleView.frame = CGRectMake(10, 182, 300, 79);
        }
        
        NSMutableArray* circleID = [[NSMutableArray alloc] init];
        NSMutableString* circleNames = [[NSMutableString alloc] initWithString:@""];
        
        for (int i = 0; i < circles.count; i++) {
            NSDictionary* circle = [circles objectAtIndex:i];
            [circleNames appendString:@" "];
            [circleNames appendString:[circle objectForKey:@"name"]];
            
            [circleID addObject:[circle objectForKey:@"id"]];
        }
        
        _circleLabel.text = circleNames;
        _circleIDString = [circleID componentsJoinedByString:@","];
        
    }
}


#pragma mark - UITextView Delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [_contentTextView resignFirstResponder];
        return NO;
    }
//
//    if ([_contentTextView.text length] > 140) {
//        _contentTextView.text = [_contentTextView.text substringToIndex:140];
//        [Helper showAlertWithTitle:nil andMessage:@"超过最大字数不能输入了"];
//        
//        return NO;
//    }
//    
//    _countLabel.text = [NSString stringWithFormat:@"%i", 140 - _contentTextView.text.length];
    
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:[self choosePlaceholder]]) {
        _contentTextView.text = @"";
    }
    
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""]) {
        
        _contentTextView.text = [self choosePlaceholder];
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    if ([textView.text length] > 140) {
        
        textView.text = [textView.text substringToIndex:140];
    }
    
    _countLabel.text = [NSString stringWithFormat:@"%i", 140 - _contentTextView.text.length];
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        //成功退出前，调用一次视图重置的方法。因为视图有可能被复用
        [self resetView];
        [self backButtonEvent];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - 相册图片拾取

//
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    [picker dismissModalViewControllerAnimated:NO];
    
    UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    [self cropImage:image];
}


- (void)cropImage:(UIImage *)image
{
    //获得图片后，进行裁剪
    GKImageCropper* cropper = [[GKImageCropper alloc] init];
    cropper.delegate = self;
    cropper.image = image;
    cropper.rescaleImage = false;
    cropper.dismissAnimated = YES;
    cropper.cropMethod = ImageCropMethodPreview;

    [self presentModalViewController:cropper animated:YES];
}

- (void)imageCropperDidFinish:(GKImageCropper *)imageCropper withImage:(UIImage *)image
{
    //压缩图片
    UIImage *newImage = [Helper resizeImage:image forStyle:PictureStyleNormal];
    NSData *imageData = [Helper compressImageData:newImage withStyle:PictureStyleNormal];

    if (_currentImageButton.tag == 1) {
        _thumbImage1 = [UIImage imageWithData:imageData];
        _thumbImageButton2.hidden = false;
    }
    
    if (_currentImageButton.tag == 2) {
        _thumbImage2 = [UIImage imageWithData:imageData];
        _thumbImageButton3.hidden = false;
    }
    
    if (_currentImageButton.tag == 3) {
        _thumbImage3 = [UIImage imageWithData:imageData];
    }
    
    [_currentImageButton setImage:image forState:UIControlStateNormal];
}


#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (actionSheet.tag) {
        case 1:
            _currentImageButton = _thumbImageButton1;
            break;
        case 2:
            _currentImageButton = _thumbImageButton2;
            break;
        case 3:
            _currentImageButton = _thumbImageButton3;
            break;
            
        default:
            break;
    }
    
    
    if (buttonIndex == 2) {
        if (actionSheet.tag == 1) {
            
            if (_thumbImage3 != nil) {
                _thumbImage1 = _thumbImage2;
                _thumbImage2 = _thumbImage3;
                _thumbImage3 = nil;
                
                [_thumbImageButton1 setImage:_thumbImage1 forState:UIControlStateNormal];
                [_thumbImageButton2 setImage:_thumbImage2 forState:UIControlStateNormal];
                [_thumbImageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
            }
            else if (_thumbImage3 == nil && _thumbImage2 != nil) {
                _thumbImage1 = _thumbImage2;
                _thumbImage2 = nil;
                
                [_thumbImageButton1 setImage:_thumbImage1 forState:UIControlStateNormal];
                [_thumbImageButton2 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
                _thumbImageButton3.hidden = true;
            }
            else {
                _thumbImage1 = nil;
                
                [_thumbImageButton1 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
                _thumbImageButton2.hidden = true;
            }
        }
        else if (actionSheet.tag == 2) {
            
            if (_thumbImage3 != nil) {
                _thumbImage2 = _thumbImage3;
                _thumbImage3 = nil;
                
                [_thumbImageButton2 setImage:_thumbImage2 forState:UIControlStateNormal];
                [_thumbImageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
            }
            else if (_thumbImage3 == nil && _thumbImage2 != nil) {
                _thumbImage2 = nil;
                [_thumbImageButton2 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
                _thumbImageButton3.hidden = true;
            }
            
        }
        else {
            
            _thumbImage3 = nil;
            
            [_thumbImageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
        }
    }
    else {
    
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        
        //拍照模式
        if (buttonIndex == 0) {
            
            //判断摄像头是否可用
            if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
                imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            }else{
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            }
            
            //访问相册模式
            [self presentModalViewController:imagePicker animated:YES];
            
        }else if (buttonIndex == 1){
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePicker.allowsEditing = NO;

            [self presentModalViewController:imagePicker animated:YES];
        }

    }
}

#pragma mark - 私有方法

/*!
 @abstract 重置视图内容，由于视图可能被复用
 */
- (void)resetView
{
//    _contentTextView.text = _L(@"holder_09");
    _contentTextView.text = [self choosePlaceholder];
    _thumbImage1 = nil;
    _thumbImage2 = nil;
    _thumbImage3 = nil;
    _circleIDString = nil;
    _circleLabel.text = @"";
    
    [_thumbImageButton1 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
    [_thumbImageButton2 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
    [_thumbImageButton3 setImage:[UIImage imageNamed:@"transaction_btn_001"] forState:UIControlStateNormal];
    
    _thumbImageButton2.hidden = true;
    _thumbImageButton3.hidden = true;
}


/*!
 @abstract 重新绘制视图内容的frame，发布商讯时有图片选择，发布推荐时则没有
 */
- (void)redrawView
{
    if (_formType == MoodFormTypeBusinessInfo) {
        _imagesView.hidden = false;
        _circleView.frame = CGRectMake(10, 265, 300, 45);
        _submitButton.frame = CGRectMake(10, _SYS_FRAME_HEIGHT - 44 - 44 -10, 300, 44);
        self.title = _L(@"vc_title_034");
    }
    else {
        _imagesView.hidden = true;
        _circleView.frame = CGRectMake(10, 182, 300, 45);
        _submitButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 300, 300, 44)];
        self.title = _L(@"vc_title_112");
    }
}

/*!
 @abstract 根据不同的表单类型设置不同的textview的placeholder
 @result 自定义的placeholder字符串
 */
- (NSString *)choosePlaceholder
{
    if (_formType == MoodFormTypeBusinessInfo) {
        
        return _L(@"holder_09");
    }
    else {
        return _L(@"holder_60");
    }
}

/*!
 @abstract 设定视图类型，重绘View
 */
- (void)setFormType:(MoodFormType)formType
{
    _formType = formType;
    
    [self redrawView];
}

@end
